<template>
  <div class="flex flex-col h-full p-4 relative">
    <!-- 返回按钮与标题 - 悬浮在页面组件顶部 -->
    <div class="absolute top-0 left-0 right-0 bg-white z-10 py-4 px-6 flex items-center mb-6">
      <el-button @click="goBack" class="mr-2" text>
        <LsiconArrowLeftFilled class="mr-1 text-2xl text-black" />
      </el-button>
      <h2 class="text-xl font-bold">Pack {{ batteryPackSN }}</h2>
    </div>

    <div class="mt-16 flex-1 flex flex-col bg-white rounded-lg shadow p-6 overflow-y-auto">
      <!-- 电池基本信息 -->
      <div class="mb-6">
        <h3 class="text-lg font-bold mb-4">Battery Information</h3>
        <div class="grid grid-cols-1 md:grid-cols-3 gap-4 p-4 border rounded">
          <div class="flex items-center">
            <span class="text-gray-500 mr-2">Battery Pack SN:</span>
            <span>{{ batteryDetail?.batteryPackSn || "-" }}</span>
          </div>
          <div class="flex items-center">
            <span class="text-gray-500 mr-2">Device SN:</span>
            <span>{{ batteryDetail?.deviceSn || "-" }}</span>
          </div>
          <div class="flex items-center">
            <span class="text-gray-500 mr-2">Fault Status:</span>
            <el-tag :type="batteryDetail?.faultStatus === 'Normal' ? 'success' : 'danger'" size="small">
              {{ batteryDetail?.faultStatus || "Normal" }}
            </el-tag>
          </div>
          <div class="flex items-center">
            <span class="text-gray-500 mr-2">Battery Type:</span>
            <span>{{ batteryDetail?.batteryType || "-" }}</span>
          </div>
          <div class="flex items-center">
            <span class="text-gray-500 mr-2">Capacity:</span>
            <span>2.4 kWh</span>
          </div>
        </div>
      </div>

      <!-- 监控选项卡 -->
      <div class="flex gap-3 mb-4">
        <el-radio-group v-model="monitoringType" class="mb-4" size="large" :disabled="loading">
          <el-radio-button label="realTime">Real-time Monitoring</el-radio-button>
          <el-radio-button label="historical">Historical Data</el-radio-button>
        </el-radio-group>

        <!-- 加载指示器 -->
        <div v-if="loading" class="flex items-center">
          <el-icon class="is-loading mr-2">
            <Loading />
          </el-icon>
          <span class="text-sm text-gray-500">Loading...</span>
        </div>

        <div class="flex items-center gap-2 mb-4">
          <div class="flex items-center gap-2 border border-transparent rounded-full p-1 hover:border-black/30 cursor-pointer transition-all duration-300" @click="prevDate">
            <UiwLeft class="text-base text-black/50" />
          </div>
          <el-date-picker v-model="selectedDate" size="large" type="date" placeholder="Select Date" format="YYYY-MM-DD" />
          <div class="flex items-center gap-2 border border-transparent rounded-full p-1 hover:border-black/30 cursor-pointer transition-all duration-300" @click="nextDate">
            <UiwRight class="text-base text-black/50" />
          </div>
        </div>
      </div>

      <!-- 内容区域：实时/历史按监控类型切换 -->
      <div v-if="monitoringType === 'realTime'">
        <RealtimeMonitoring />
      </div>
      <div v-else class="grid grid-cols-1 gap-6">
        <!-- 最大/最小电池电压图表 -->
        <div class="border rounded p-4">
          <h4 class="text-base font-bold mb-4">Max/Min Cell Voltage</h4>
          <div ref="maxMinChartRef" style="height: 300px" class="chart"></div>
        </div>

        <!-- 电池组总电压图表 -->
        <div class="border rounded p-4">
          <h4 class="text-base font-bold mb-4">Total Voltage</h4>
          <div ref="totalVoltageChartRef" style="height: 300px" class="chart"></div>
        </div>

        <!-- 电池组总电流图表 -->
        <div class="border rounded p-4">
          <h4 class="text-base font-bold mb-4">Total Current</h4>
          <div ref="totalCurrentChartRef" style="height: 300px" class="chart"></div>
        </div>

        <!-- 电池组温度图表 -->
        <div class="border rounded p-4">
          <h4 class="text-base font-bold mb-4">Temperature</h4>
          <div ref="temperatureChartRef" style="height: 300px" class="chart"></div>
        </div>

        <!-- 电池组SOC图表 -->
        <div class="border rounded p-4">
          <h4 class="text-base font-bold mb-4">SOC</h4>
          <div ref="socChartRef" style="height: 300px" class="chart"></div>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, computed, watch, onBeforeUnmount, nextTick } from "vue";
import { ArrowLeft, Loading } from "@element-plus/icons-vue";
import * as echarts from "echarts/core";
import { LineChart } from "echarts/charts";
import { GridComponent, TooltipComponent, TitleComponent, LegendComponent } from "echarts/components";
import LsiconArrowLeftFilled from "~icons/lsicon/arrow-left-filled";
import UiwLeft from "~icons/uiw/left";
import UiwRight from "~icons/uiw/right";
import { CanvasRenderer } from "echarts/renderers";
import type { BatteryPackItem } from "../data";
import { mockBatteryPacks } from "../data";
import RealtimeMonitoring from "./BatteryPackDetail/RealtimeMonitoring.vue";
import { bmsApi } from "@/api/bms";

// 注册必须的组件
echarts.use([CanvasRenderer, LineChart, GridComponent, TooltipComponent, TitleComponent, LegendComponent]);

// Props
interface Props {
  batteryId: string;
}

const props = defineProps<Props>();

// Emits
const emit = defineEmits<{
  "go-back": [];
}>();

// 图表DOM引用
const maxMinChartRef = ref<HTMLElement | null>(null);
const totalVoltageChartRef = ref<HTMLElement | null>(null);
const totalCurrentChartRef = ref<HTMLElement | null>(null);
const temperatureChartRef = ref<HTMLElement | null>(null);
const socChartRef = ref<HTMLElement | null>(null);

// echarts实例
let maxMinChart: echarts.ECharts | null = null;
let totalVoltageChart: echarts.ECharts | null = null;
let totalCurrentChart: echarts.ECharts | null = null;
let temperatureChart: echarts.ECharts | null = null;
let socChart: echarts.ECharts | null = null;
let hasResizeListener = false;

// 获取电池SN
const batteryPackSN = computed(() => props.batteryId);
console.log("batteryPackSN", batteryPackSN.value);

// 监控类型
const monitoringType = ref("realTime");
const selectedDate = ref(new Date());

// 日期切换函数
const prevDate = () => {
  const date = new Date(selectedDate.value);
  date.setDate(date.getDate() - 1);
  selectedDate.value = date;
};

const nextDate = () => {
  const date = new Date(selectedDate.value);
  date.setDate(date.getDate() + 1);
  selectedDate.value = date;
};

// 获取电池详情
const batteryDetail = ref<BatteryPackItem | null>(null);

// 加载状态
const loading = ref(false);

// 共用时间轴数据
const hours = ["02:00", "06:00", "08:00", "10:00", "12:00", "14:00", "16:00", "18:00", "20:00", "20:00", "22:00", "24:00"];

// ========== 电池电压数据 ==========
// 最大电池电压数据 - 单位: V
// 表示电池组中电压最高的单体电池电压，通常比最小电压高0.5-0.8V
const maxVoltageData = [0.8, 1.2, 1.5, 0.9, 2.2, 0.3, 0.4, 0.8, 1.8, 1.9, 2.2, 2.1];

// 最小电池电压数据 - 单位: V
// 表示电池组中电压最低的单体电池电压
const minVoltageData = [1.5, 1.7, 2.0, 1.6, 2.7, 0.9, 0.8, 1.2, 2.2, 2.4, 2.7, 2.6];

// ========== 电池组总电压数据 ==========
// 电池组总电压数据 - 单位: V
// 表示整个电池组的总输出电压，通常为所有单体电池电压的总和
const totalVoltageData = [1.2, 1.5, 1.8, 1.5, 1.7, 1.2, 2.0, 2.5, 3.0, 2.3, 2.0, 3.0];

// ========== 电池组电流数据 ==========
// 电池组总电流数据 - 单位: A
// 表示整个电池组的输出电流，充电时为正值，放电时为负值
const totalCurrentData = [1.0, 0.2, 0.5, 0.3, 1.5, 2.8, 3.0, 3.2, 3.5, 2.5, 2.0, 3.0];

// ========== 电池组温度数据 ==========
// 电池组温度数据 - 单位: °C
// 表示电池组的工作温度，正常范围通常在20-40°C之间
const temperatureData = [1.1, 0.0, 0.6, 0.2, 1.5, 3.0, 3.0, 2.8, 3.2, 2.5, 1.9, 3.0];

// ========== 电池组SOC数据 ==========
// 电池荷电状态(State of Charge)数据 - 单位: %
// 表示电池剩余电量百分比，100%表示满电，0%表示没电
const socData = [1.0, 0.0, 0.5, 0.2, 1.5, 3.0, 3.0, 3.5, 2.8, 3.0, 2.0, 3.0];

// ========== 接口请求函数 ==========

// 获取实时数据
const fetchRealTimeData = async () => {
  console.log("fetchRealTimeData", batteryPackSN.value);
  try {
    loading.value = true;
    const params = {
      batteryCode: batteryPackSN.value
      // deviceId: parseInt(batteryDetail.value.deviceSn) || 0
    };

    const response = await bmsApi.getRealData(params);
    // 处理实时数据响应
    if (response && response.code === 0) {
      // 这里可以根据实际返回的数据结构来处理实时数据
      // 例如：更新实时监控组件的数据
      console.log("Real-time data:", response.data);
      batteryDetail.value = response.data?.batteryPackReal;

      // 示例：如果需要传递数据给 RealtimeMonitoring 组件
      // 可以通过 emit 或者 provide/inject 的方式传递数据
    }
  } catch (error) {
    console.error("Failed to fetch real-time data:", error);
  } finally {
    loading.value = false;
  }
};

// 获取历史数据
const fetchHistoryData = async () => {
  // if (!batteryDetail.value) return;

  try {
    loading.value = true;
    const params = {
      batteryPackSN: batteryPackSN.value,
      // deviceSN: batteryDetail.value.deviceSn,
      daytime: selectedDate.value.toISOString().split("T")[0] // 格式化为 YYYY-MM-DD
    };

    const response = await bmsApi.getHistoryData(params);
    // 处理历史数据响应
    if (response && response.code === 0) {
      // 这里可以根据实际返回的数据结构来更新图表数据
      console.log("History data:", response.data);

      // 示例：根据返回的数据更新图表数据
      // const historyData = response.data;
      // if (historyData) {
      //   // 更新各种图表数据
      //   maxVoltageData.splice(0, maxVoltageData.length, ...historyData.maxVoltage);
      //   minVoltageData.splice(0, minVoltageData.length, ...historyData.minVoltage);
      //   totalVoltageData.splice(0, totalVoltageData.length, ...historyData.totalVoltage);
      //   totalCurrentData.splice(0, totalCurrentData.length, ...historyData.totalCurrent);
      //   temperatureData.splice(0, temperatureData.length, ...historyData.temperature);
      //   socData.splice(0, socData.length, ...historyData.soc);
      // }

      // 更新图表数据后重新渲染图表
      nextTick(() => {
        updateCharts();
      });
    }
  } catch (error) {
    console.error("Failed to fetch history data:", error);
  } finally {
    loading.value = false;
  }
};

// 根据监控类型获取数据
const fetchDataByType = () => {
  if (monitoringType.value === "realTime") {
    fetchRealTimeData();
  } else if (monitoringType.value === "historical") {
    fetchHistoryData();
  }
};

// ========== 图表配置函数 ==========

// 最大/最小电压图表配置
const getMaxMinVoltageOption = () => {
  return {
    tooltip: {
      trigger: "axis"
    },
    legend: {
      data: ["Max Cell Voltage", "Min Cell Voltage"]
    },
    grid: {
      left: "3%",
      right: "4%",
      bottom: "3%",
      containLabel: true
    },
    xAxis: {
      type: "category",
      boundaryGap: false,
      data: hours
    },
    yAxis: {
      type: "value",
      name: "(V)"
    },
    series: [
      {
        name: "Max Cell Voltage",
        type: "line",
        data: maxVoltageData,
        itemStyle: {
          color: "#67C23A"
        }
      },
      {
        name: "Min Cell Voltage",
        type: "line",
        data: minVoltageData,
        itemStyle: {
          color: "#409EFF"
        }
      }
    ]
  };
};

// 电池组总电压图表配置
const getTotalVoltageOption = () => {
  return {
    tooltip: {
      trigger: "axis"
    },
    grid: {
      left: "3%",
      right: "4%",
      bottom: "3%",
      containLabel: true
    },
    xAxis: {
      type: "category",
      boundaryGap: false,
      data: hours
    },
    yAxis: {
      type: "value",
      name: "(V)"
    },
    series: [
      {
        type: "line",
        data: totalVoltageData,
        itemStyle: {
          color: "#E6A23C"
        },
        areaStyle: {
          opacity: 0.3
        }
      }
    ]
  };
};

// 电池组总电流图表配置
const getTotalCurrentOption = () => {
  return {
    tooltip: {
      trigger: "axis"
    },
    grid: {
      left: "3%",
      right: "4%",
      bottom: "3%",
      containLabel: true
    },
    xAxis: {
      type: "category",
      boundaryGap: false,
      data: hours
    },
    yAxis: {
      type: "value",
      name: "(A)" // 电流单位
    },
    series: [
      {
        type: "line",
        data: totalCurrentData,
        itemStyle: {
          color: "#409EFF" // 蓝色
        },
        areaStyle: {
          opacity: 0.3
        }
      }
    ]
  };
};

// 电池组温度图表配置
const getTemperatureOption = () => {
  return {
    tooltip: {
      trigger: "axis"
    },
    grid: {
      left: "3%",
      right: "4%",
      bottom: "3%",
      containLabel: true
    },
    xAxis: {
      type: "category",
      boundaryGap: false,
      data: hours
    },
    yAxis: {
      type: "value",
      name: "(°C)" // 温度单位
    },
    series: [
      {
        type: "line",
        data: temperatureData,
        itemStyle: {
          color: "#E6A23C" // 橙色
        },
        areaStyle: {
          opacity: 0.3
        }
      }
    ]
  };
};

// 电池组SOC图表配置
const getSocOption = () => {
  return {
    tooltip: {
      trigger: "axis"
    },
    grid: {
      left: "3%",
      right: "4%",
      bottom: "3%",
      containLabel: true
    },
    xAxis: {
      type: "category",
      boundaryGap: false,
      data: hours
    },
    yAxis: {
      type: "value",
      name: "(%)" // SOC单位
    },
    series: [
      {
        type: "line",
        data: socData,
        itemStyle: {
          color: "#6366F1" // 紫色
        },
        areaStyle: {
          opacity: 0.3
        }
      }
    ]
  };
};

// 初始化图表
const initCharts = () => {
  // 初始化最大/最小电压图表
  if (maxMinChartRef.value && !maxMinChart) {
    maxMinChart = echarts.init(maxMinChartRef.value);
    maxMinChart.setOption(getMaxMinVoltageOption());
  }

  // 初始化总电压图表
  if (totalVoltageChartRef.value && !totalVoltageChart) {
    totalVoltageChart = echarts.init(totalVoltageChartRef.value);
    totalVoltageChart.setOption(getTotalVoltageOption());
  }

  // 初始化总电流图表
  if (totalCurrentChartRef.value && !totalCurrentChart) {
    totalCurrentChart = echarts.init(totalCurrentChartRef.value);
    totalCurrentChart.setOption(getTotalCurrentOption());
  }

  // 初始化温度图表
  if (temperatureChartRef.value && !temperatureChart) {
    temperatureChart = echarts.init(temperatureChartRef.value);
    temperatureChart.setOption(getTemperatureOption());
  }

  // 初始化SOC图表
  if (socChartRef.value && !socChart) {
    socChart = echarts.init(socChartRef.value);
    socChart.setOption(getSocOption());
  }
};

// 更新图表
const updateCharts = () => {
  // 更新最大/最小电压图表
  if (maxMinChart) {
    maxMinChart.setOption(getMaxMinVoltageOption());
  }

  // 更新总电压图表
  if (totalVoltageChart) {
    totalVoltageChart.setOption(getTotalVoltageOption());
  }

  // 更新总电流图表
  if (totalCurrentChart) {
    totalCurrentChart.setOption(getTotalCurrentOption());
  }

  // 更新温度图表
  if (temperatureChart) {
    temperatureChart.setOption(getTemperatureOption());
  }

  // 更新SOC图表
  if (socChart) {
    socChart.setOption(getSocOption());
  }
};

// 处理窗口大小变化
const handleResize = () => {
  // 自适应调整所有图表大小
  maxMinChart?.resize();
  totalVoltageChart?.resize();
  totalCurrentChart?.resize();
  temperatureChart?.resize();
  socChart?.resize();
};

const addResizeListener = () => {
  if (!hasResizeListener) {
    window.addEventListener("resize", handleResize);
    hasResizeListener = true;
  }
};

const removeResizeListener = () => {
  if (hasResizeListener) {
    window.removeEventListener("resize", handleResize);
    hasResizeListener = false;
  }
};

// 监听监控类型变化
watch(monitoringType, (val) => {
  console.log("监听monitoringType", monitoringType, val);
  // 切到历史页：若未初始化则初始化，否则仅更新
  if (val === "historical") {
    nextTick(() => {
      if (!maxMinChart && maxMinChartRef.value) {
        initCharts();
        addResizeListener();
      } else {
        updateCharts();
      }
      // 获取历史数据
      fetchHistoryData();
    });
  } else if (val === "realTime") {
    // 切到实时页：销毁图表与监听，避免下一次切回绑定旧 DOM 导致空白
    disposeCharts();
    removeResizeListener();
    // 获取实时数据
    fetchRealTimeData();
  }
});

// 监听日期变化
watch(selectedDate, () => {
  if (monitoringType.value === "historical") {
    // 获取新日期的历史数据
    fetchHistoryData();
  }
});

// 加载电池详情数据
onMounted(() => {
  // 在实际应用中，这里应该发送API请求获取详情
  batteryDetail.value = mockBatteryPacks.find((item) => item.batteryPackSn === batteryPackSN.value) || null;

  // 默认实时页，不立即初始化图表；历史页可见时再初始化
  nextTick(() => {
    if (monitoringType.value === "historical") {
      initCharts();
      addResizeListener();
      // 获取历史数据
      fetchHistoryData();
    } else if (monitoringType.value === "realTime") {
      // 获取实时数据
      fetchRealTimeData();
    }
  });
});

// 销毁图表实例
const disposeCharts = () => {
  maxMinChart?.dispose();
  totalVoltageChart?.dispose();
  totalCurrentChart?.dispose();
  temperatureChart?.dispose();
  socChart?.dispose();
  maxMinChart = null;
  totalVoltageChart = null;
  totalCurrentChart = null;
  temperatureChart = null;
  socChart = null;
};

onBeforeUnmount(() => {
  removeResizeListener();
  disposeCharts();
});

// 返回上一页
const goBack = () => {
  emit("go-back");
};
</script>

<style scoped>
.chart {
  width: 100%;
  height: 100%;
}
</style>
